package com.gistmap.ntdc.service;

import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.gistmap.ntdc.exception.ErrorItems;
import com.gistmap.ntdc.exception.ServiceException;
import com.gistmap.ntdc.persistence.domain.User;
import com.gistmap.ntdc.persistence.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author zhangran
 * @date 2018/12/19
 */
@Component
@Transactional(rollbackFor = ServiceException.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User findByToken(String token){
        return userRepository.findByToken(token);
    }

    public User find(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new ServiceException(ErrorItems.USER_NOT_FIND));
    }

    public User save(WxMaUserInfo userInfo, String token){
        if (userInfo == null || userInfo.getOpenId() == null) {
            throw new ServiceException(ErrorItems.USER_INFO_ILLEGAL);
        }
        Date now = new Date();
        User byOpenId = userRepository.findAllByOpenId(userInfo.getOpenId());
        User user = (byOpenId == null) ? new User(userInfo) : byOpenId;
        user.setToken(token);
        user.setUpdatedTime(now);
        return userRepository.save(user);
    }
}
